package com.jarvis.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Map;

/**
 * 用于模拟HTTP请求中GET/POST方式
 * 
 * @author Jack
 *
 */
public class HttpUtils {
	
	 // HTTP内容类型。相当于form表单的形式，提交数据
    private static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

    // HTTP内容类型。相当于Json的形式，提交数据
    private static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
    
	/**
	 * 发送GET请求
	 * 
	 * @param url
	 *            目的地址
	 * @param parameters
	 *            请求参数，Map类型。
	 * @return 远程响应结果
	 */
	public static String sendGet(String url, Map<String, String> parameters) {
		String result = "";
		BufferedReader in = null;// 读取响应输入流
		StringBuffer sb = new StringBuffer();// 存储参数
		String params = "";// 编码之后的参数
		String full_url = "";
		try {
			if (parameters == null || parameters.size() == 0) {
				full_url = url;
			} else {
				params = getRequestParams(parameters, sb, params);
				full_url = url + "?" + params;
			}
			// System.out.println(full_url);
			// 创建URL对象
			java.net.HttpURLConnection httpConn = getConnection(full_url);
			// 建立实际的连接
			httpConn.connect();
			// 响应头部获取
			// Map<String, List<String>> headers = httpConn.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : headers.keySet()) {
			// System.out.println(key + "\t：\t" + headers.get(key));
			// }
			// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 作者:Jack 日期:2017年9月26日下午11:05:15
	 * 
	 * @param full_url
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 *             返回值:java.net.HttpURLConnection 返回值说明:创建连接
	 */
	private static java.net.HttpURLConnection getConnection(String full_url) throws MalformedURLException, IOException {
		java.net.URL connURL = new java.net.URL(full_url);
		// 打开URL连接
		java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
		//设置通用属性
		httpConn.setRequestProperty("Accept", "*/*");
		httpConn.setRequestProperty("Connection", "Keep-Alive");
		httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
		//设置通用的Content-Type
		httpConn.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
		return httpConn;
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url
	 *            目的地址
	 * @param parameters
	 *            请求参数，Map类型。
	 * @return 远程响应结果
	 */
	public static String sendPost(String url, Map<String, String> parameters) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();// 处理请求参数
		String params = "";// 编码之后的参数
		try {
			if (parameters == null || parameters.size() == 0) {
			} else {
				// 编码请求参数
				params = getRequestParams(parameters, sb, params);
			}
			java.net.HttpURLConnection httpConn = getPostConnection(url);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			if (params != "") {
				out.write(params);
			}
			// System.out.println(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 作者:Jack 日期:2017年9月26日下午11:01:42
	 * 
	 * @param url
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 *             返回值:java.net.HttpURLConnection 返回值说明:创建Post连接
	 */
	private static java.net.HttpURLConnection getPostConnection(String url) throws MalformedURLException, IOException {
		java.net.HttpURLConnection httpConn = getConnection(url);
		// 设置POST方式
		httpConn.setDoInput(true);
		httpConn.setDoOutput(true);
		return httpConn;
	}

	/**
	 * 作者:Jack 日期:2017年9月26日下午10:57:20
	 * 
	 * @param parameters
	 * @param sb
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 *             返回值:String 返回值说明:打包请求参数
	 */
	private static String getRequestParams(Map<String, String> parameters, StringBuffer sb, String params)
			throws UnsupportedEncodingException {
		if (parameters.size() == 1) {
			for (String name : parameters.keySet()) {
				sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
			}
			params = sb.toString();
		} else if (parameters.size() > 1) {
			for (String name : parameters.keySet()) {
				sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"))
						.append("&");
			}
			String temp_params = sb.toString();
			params = temp_params.substring(0, temp_params.length() - 1);
		}
		return params;
	}

	/**
	 * Author:Jack Time:2017年9月5日下午2:20:26
	 * 
	 * @param url
	 * @param parameters
	 * @return Return:String Description:发送Post请求，并且发送的是Json格式的数据。
	 */
	public static String sendPostJson(String url, Map<String, String> parameters) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		String params = "";// 编码之后的参数
		try {
			if (parameters != null && parameters.size() > 0) {
				params = FastJsonUtil.toJSONString(parameters);
			}
			java.net.HttpURLConnection httpConn = getPostConnection(url);
			//设置json格式的请求
			httpConn.setRequestProperty("Content-Type", CONTENT_TYPE_JSON_URL);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			if (params != "") {
				out.write(params);
			}
			// System.out.println(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}